package com.ruoyi.mes.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.mes.domain.DeviceStatus;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

@Component
public class MqttClientUtil {

    @Autowired
    private MqttClient mqttClient;

    DeviceStatus deviceStatus;

    // 存储设备状态（设备ID -> 最新状态）
    private final Map<String, DeviceStatus> deviceStatusMap = new ConcurrentHashMap<>();


    // 存储设备回调（设备ID -> 回调函数）
    private final Map<String, Consumer<DeviceStatus>> callbackMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println(cause.getCause());
            }
            //订阅主题回调函数
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
//                 System.out.printf("收到消息 [主题: %s] [内容: %s]%n",
//                         topic, new String(message.getPayload()));
                handleDeviceStatusMessage(topic, message);
            }
            //发布主题回调函数
            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                // 消息发送成功回调
                System.out.println("消息发布成功: " + token.getMessageId());
            }
        });
    }



    public void publish(String topic, String message) throws MqttException {
//      MqttMessage mqttMessage = new MqttMessage(Objects.toString(devicecommand).getBytes());

        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(1);
        mqttMessage.setRetained(false);
        mqttClient.publish(topic,mqttMessage);
    }
    public void subscribe(String topic) throws MqttException {
        mqttClient.subscribe(topic);;
    }

    public void handleDeviceStatusMessage(String topic, MqttMessage message) {

        String payload = new String(message.getPayload());
        System.out.printf("收到设备状态消息 [主题: %s] [内容: %s]%n", topic, payload);
        try {
            // 解析JSON消息
            JSONObject json = JSON.parseObject(payload);

            // 提取设备ID和状态
            String device= json.getString("device");
            String status = json.getString("status");

//            if(status.equals("null")){
//                return;
//            }
            // 创建设备状态对象
            deviceStatus = new DeviceStatus(device, status);

            // 存储设备状态
//            deviceStatusMap.computeIfAbsent(device, k -> new ArrayList<>()).add(deviceStatus);

            deviceStatusMap.put(device,deviceStatus);
            System.out.println("数组内存"+deviceStatusMap);
            // 更新状态管理器
//            updateStatus(device, deviceStatus);

            System.out.println("设备状态已更新: " + deviceStatus.getDevice()+"返回"+deviceStatusMap.get(device)+"   仿真动画已完成");
        }
        catch (Exception e) {
            System.err.println("设备状态消息解析失败: " + e.getMessage());
            System.err.println("原始消息: " + payload);
        }
    }

    public void updateStatus(String deviceId, DeviceStatus status) {

        // 执行注册的回调
        Consumer<DeviceStatus> callback = callbackMap.get(deviceId);
        if (callback != null) {
            callback.accept(status);
        }
    }
    /**
     * 获取设备状态
     */
    public DeviceStatus getStatus(String deviceId) {
        return deviceStatusMap.getOrDefault(deviceId, new DeviceStatus(deviceId,"balck"));
    }

    /**
     * 注册状态回调
     */
    public void registerCallback(String deviceId, Consumer<DeviceStatus> callback) {
         callbackMap.put(deviceId, callback);
    }

    public DeviceStatus getDeviceStatus(String device) {
        // 查询设备状态（设备ID -> 最新状态）返回String/DeviceStatus都行
//        return deviceStatusMap.getOrDefault(deviceId, new ArrayList<>());
        return deviceStatusMap.get(device);
    }

    public Map<String, DeviceStatus> getAllDeviceStatuses(){

        return new ConcurrentHashMap<>(deviceStatusMap);
    }









//    @Autowired
//    private MqttClient mqttClient;
//
//    DeviceStatus deviceStatus;
//
//    // 存储主题与回调的映射关系
//    private final Map<String, MessageCallback> topicCallbacks = new ConcurrentHashMap<>();
//
//    // 存储设备状态数据（主题 -> 最新消息）
//    private final Map<String, JSONObject> deviceStatusStore = new ConcurrentHashMap<>();
//
//    @PostConstruct
//    public void init() {
//         mqttClient.setCallback(new MqttCallback() {
//             @Override
//             public void connectionLost(Throwable cause) {
//                 System.out.println(cause.getCause());
//             }
//             //订阅主题回调函数
//             @Override
//             public void messageArrived(String topic, MqttMessage message) throws Exception {
//                 handleDeviceStatusMessage(topic, message);
//             }
//             //发布主题回调函数
//             @Override
//             public void deliveryComplete(IMqttDeliveryToken token) {
//                 // 消息发送成功回调
//                 System.out.println("消息发布成功: " + token.getMessageId());
//             }
//         });
//    }
//
//
//
//    public void publish(String topic, String message) throws MqttException {
////      MqttMessage mqttMessage = new MqttMessage(Objects.toString(devicecommand).getBytes());
//
//        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
//        mqttMessage.setQos(1);
//        mqttMessage.setRetained(false);
//        mqttClient.publish(topic,mqttMessage);
//
//    }
//    public void subscribe(String topic,MessageCallback messageCallback) throws MqttException {
//
//        topicCallbacks.put(topic,messageCallback);
//        mqttClient.subscribe(topic);
//
//
//    }
//
//    private void handleDeviceStatusMessage(String topic, MqttMessage message) {
//
//        String payload = new String(message.getPayload());
//        System.out.printf("收到设备状态消息 [主题: %s] [内容: %s]%n", topic, payload);
//        try {
//            JSONObject json = JSONObject.parseObject(payload);
//            deviceStatusStore.put(topic, json);
//        }
//        catch (Exception e) {
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("raw",jsonObject);
//        }
//
//        MessageCallback callback = topicCallbacks.get(topic);
//        if (callback != null) {
//            callback.handleMessage(message);
//        }
//
//
//    }
//
//    //拿到回调函数
//    public MessageCallback getTopicCallback(String topic) {
//        return topicCallbacks.get(topic);
//    }
//
//    //获取设备状态
//    public JSONObject getDeviceStatus(String topic) {
//          return deviceStatusStore.get(topic);
//    }
//
//    //获取全部设备状态
//    public Map<String, JSONObject> getAllDeviceStatuses() {
//        return new ConcurrentHashMap<>(deviceStatusStore);
//    }


}
